<script setup lang="ts">
import { ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { ${lowerClassName}AddApi, ${lowerClassName}EditApi, ${lowerClassName}QueryByIdApi } from '#/api/${modulePath}/${businessPath}';

const record = ref({});
const [Form, formApi] = useVbenForm({
    showDefaultActions: false,
    wrapperClass: 'grid-cols-2',
    commonConfig: {
        componentProps: {
            class: 'w-full',
        },
    },
    schema: [
        <#list fields as field>
        {
            component: 'Input',
            componentProps: {
                placeholder: '请输入${field.fieldAnnotation}',
            },
            fieldName: '${field.fieldName}',
            label: '${field.fieldAnnotation}',
            rules: 'required',
        },
        </#list>
    ],
});

const [Drawer, drawerApi] = useVbenDrawer({
    title: '${functionName}',
    destroyOnClose: true,
    onCancel: () => {
        drawerApi.close();
    },
    onConfirm: onsubmit,
    onOpenChange(isOpen: boolean) {
        if (isOpen) {
            record.value = drawerApi.getData<Record<string, any>>();
            drawerApi.setState({ title: `${formTitleName}${functionName}` });
            if (record.value.id) {
                initFun();
            }
        }
    },
});
async function initFun() {
    const res = await ${lowerClassName}QueryByIdApi({ id: record.value.id });
    await formApi.setValues(res, false);
}
async function onSubmit() {
    const { valid } = await formApi.validate();
    const values = await formApi.getValues();
    if (valid) {
        if (record.value.id) {
            const msg = await ${lowerClassName}EditApi(values);
            message.success(msg);
            await modalApi.close();
        } else {
            const msg = await ${lowerClassName}AddApi(values);
            message.success(msg);
            await modalApi.close();
        }
    }
}
</script>

<template>
    <Drawer>
        <Form />
    </Drawer>
</template>
